<template>
    <el-row class="login-row">
        <el-col :span="6" :offset="9">
            <el-card class="box-card" shadow="hover">
                <div slot="header" class="clearfix">
                    <div>科泰购后台登录</div>
                </div>
                <el-form :model="loginForm" status-icon :rules="rules" ref="loginFormRef" label-width="80px"
                    class="demo-loginForm">
                    <el-form-item label="用户名" prop="username">
                        <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="loginForm.password" show-password autocomplete="off">
                        </el-input>
                    </el-form-item>
                    <div class="login-btn">
                        <el-button type="primary" @click="submitForm">登录</el-button>
                    </div>
                </el-form>
            </el-card>
        </el-col>
    </el-row>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import axios from 'axios'
import { useUserStore } from '@/store' // 导入用户Store

const router = useRouter()
const userStore = useUserStore() // 获取用户Store实例
const loginFormRef = ref(null)

const loginForm = reactive({
    username: '',
    password: ''
})

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名！', trigger: 'blur' },
        { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码！', trigger: 'blur' },
        { pattern: /^\w{6,}$/, message: '密码为6位以上数字字母下划线组合！', trigger: 'blur' }
    ]
})

const submitForm = () => {
    loginFormRef.value.validate((valid) => {
        if (valid) {
            const queryStr = qs.stringify(loginForm)
            axios.post('/api/login', queryStr)
                .then((res) => {
                    if (res.data.code === 0) {
                        const userInfo = res.data.data
                        ElMessage.success(`${userInfo.nickname}登录成功！`)
                        userStore.login(userInfo)
                        router.push({ path: '/main' }) 
                    } else {
                        ElMessage.error(res.data.msg)
                    }
                })
        } else {
            ElMessage.error('校验失败，请重新填写！')
            return false
        }
    })
}
</script>

<style>
.login-row {
    margin-top: 100px;
    min-width: 800px;
}

.login-row .login-btn {
    text-align: center;
}
</style>